package com.shopx.gen.utils;

import java.io.*;

public class FileUtil {
  public static boolean createFile(String savePath, String fileName, String filecontent) {
    Boolean bool = false;
    String filenameTemp = "";
    filenameTemp = savePath + fileName;// 文件路径+名称+文件类型
    File file = new File(filenameTemp);
    try {
      File dir = file.getParentFile();
      if (!dir.exists()) {
        dir.mkdirs();
      } else {
        file.delete();
        dir.mkdirs();
      }
      file.createNewFile();
      bool = true;
      // 创建文件成功后，写入内容到文件里
      writeFileContent(filenameTemp, filecontent);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return bool;
  }

  public static boolean writeFileContent(String filepath, String newstr) throws IOException {
    Boolean bool = false;
    String filein = newstr + "\r\n";// 新写入的行，换行
    String temp = "";

    FileInputStream fis = null;
    InputStreamReader isr = null;
    BufferedReader br = null;
    FileOutputStream fos = null;
    PrintWriter pw = null;
    try {
      File file = new File(filepath);// 文件路径(包括文件名称)
      // 将文件读入输入流
      fis = new FileInputStream(file);
      isr = new InputStreamReader(fis);
      br = new BufferedReader(isr);
      StringBuffer buffer = new StringBuffer();

      // 文件原有内容
      for (int i = 0; (temp = br.readLine()) != null; i++) {
        buffer.append(temp);
        // 行与行之间的分隔符 相当于“\n”
        buffer = buffer.append(System.getProperty("line.separator"));
      }
      buffer.append(filein);

      fos = new FileOutputStream(file);
      pw = new PrintWriter(fos);
      pw.write(buffer.toString().toCharArray());
      pw.flush();
      bool = true;
    } catch (Exception e) {
      // TODO: handle exception
      e.printStackTrace();
    } finally {
      // 不要忘记关闭
      if (pw != null) {
        pw.close();
      }
      if (fos != null) {
        fos.close();
      }
      if (br != null) {
        br.close();
      }
      if (isr != null) {
        isr.close();
      }
      if (fis != null) {
        fis.close();
      }
    }
    return bool;
  }

  public static void main(String[] args) {
    try {
//			File file = new File(
//					"/Volumes/WORK/workspace/shopx/shopx-root/shopx-service-core/src/main/java/com/shopx/pub/service/ITSysTableColumnsService.java");

      File file = new File("/Users/lituo/Downloads/build.gradle");
      boolean result = file.delete();
      System.out.println(result);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
